<template>
  <a-modal :title="modalTitle"
           :width="1100"
           :visible="visible"
           :confirmLoading="confirmLoading"
           :maskClosable="false"
           @ok="handleSubmit"
           @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form"
              style="max-height: 500px;overflow-y: auto;overflow-x: hidden;">
        <a-form-item label="业务ID"
                     :labelCol="labelCol"
                     :wrapperCol="wrapperCol"
                     v-show="false">
          <a-input v-if="modalOpera==1"
                   v-decorator="['id', {rules: [{required: true}]}]" />
        </a-form-item>
        <p>
          基础信息
          <a-icon type="right" />
        </p>
        <a-row :gutter="12">
          <a-col :xl="{span: 8}"
                 :lg="{span: 8}"
                 :md="{span: 12}">
            <a-form-item label="模型名称"
                         :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-input v-decorator="['name', {rules: [{required: true, min: 2, message: '请输入至少二个字符的规则！'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :xl="{span: 16}"
                 :lg="{span: 8}"
                 :md="{span: 12}">
            <a-form-item label="模型选项"
                         :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-checkbox :value="moption.value"
                          :key="moption.value"
                          :checked="moptions.indexOf(moption.value) >=0"
                          v-for="moption in modelOptions"
                          @change="onChangeMoption">{{ moption.label }}</a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="12">
          <a-col :xl="{span: 8}"
                 :lg="{span: 8}"
                 :md="{span: 24}">
            <a-form-item label="内容模板"
                         :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-input-search v-decorator="['templatePath', {rules: [{required: true, min: 3, message: '请输入至少三个字符的规则！'}]}]"
                              @search="onSearchTemp"
                              disabled />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider dashed />

        <p>
          内容系统字段
          <a-icon type="right" />
        </p>

        <a-row :gutter="6"
               v-for="(field,index) in fields"
               :key="index">
          <a-col :xl="{span: 5}"
                 :lg="{span: 8}"
                 :md="{span: 24}">
            <a-form-item :label="field.fieldNote"
                         :labelCol="labelCol"
                         :wrapperCol="{xs: {span: 24},sm:{ span: 4}}">
              <a-checkbox :value="field.fieldName"
                          :checked="field.initCheck"
                          v-if="!field.visibleCheck"
                          @change="checkDefaultField"></a-checkbox>
            </a-form-item>
          </a-col>

          <a-col :xl="{span: 6}"
                 :lg="{span: 6}"
                 :md="{span: 24}">
            <a-form-item :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <p>{{ field.fieldName }}( {{ field.fieldType }} )</p>
            </a-form-item>
          </a-col>

          <a-col :xl="{span: 5}"
                 :lg="{span: 8}"
                 :md="{span: 24}"
                 v-if="field.visibleSwitch && checkDefaultFields.indexOf(field.fieldName)>=0">
            <a-form-item label="必填"
                         :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-switch v-model="field.initSwitch" />
            </a-form-item>
          </a-col>

          <a-col :xl="{span: 5}"
                 :lg="{span: 8}"
                 :md="{span: 24}"
                 v-if="checkDefaultFields.indexOf(field.fieldName)>=0">
            <a-form-item :labelCol="labelCol"
                         :wrapperCol="wrapperCol">
              <a-input v-model="field.reFieldNote" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-divider dashed />
        <p>
          扩展字段
          <a-icon type="right" />
        </p>
        <div class="table-operator">
          <a-button style="margin-bottom: 5px;"
                    type="primary"
                    icon="plus"
                    v-has="{perm:'role:save'}"
                    @click="handleAddExtendsField">添加字段</a-button>
          <span style="font-size:12px">PS:内容扩展字段(source,sourceUrl,text)不可用增加行</span>
        </div>

        <a-table bordered
                 :pagination="false"
                 ref="table"
                 rowKey="id"
                 :columns="columns"
                 size="small"
                 :dataSource="dataSource">
          <template v-for="col in extendsField"
                    :slot="col.name"
                    slot-scope="text, record, index">
            <a-form-item :key="col.name"
                         style="padding:0;margin:0">
              <a-input-number v-if="col.type === 'number' "
                              :min="0"
                              v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                              @change="e => handleChange(e, record.id, col.name, index,col.type)" />
              <a-input v-if="col.type === 'text' "
                       :min="0"
                       v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                       @change="e => handleChange(e, record.id, col.name, index,col.type)" />

              <a-radio v-if="col.type === 'radio' "
                       v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                       @change="e => handleChange(e, record.id, col.name, index,col.type)"></a-radio>

              <a-checkbox v-if="col.type === 'checkbox' "
                          :checked="text"
                          v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                          @change="e => handleChange(e, record.id, col.name, index,col.type)"></a-checkbox>

              <a-textarea v-if="col.type === 'textarea' "
                          :rows="1"
                          v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                          @change="e => handleChange(e, record.id, col.name, index,col.type)"></a-textarea>

              <a-select v-if="col.type === 'select'"
                        :options="inputType"
                        v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: true, message: '不能为空' }],
                   initialValue:text,validateTrigger: 'change'}
                ]"
                        @change="e => handleChange(e, record.id, col.name, index,col.type)"></a-select>
            </a-form-item>
          </template>
          <span slot="action"
                slot-scope="text, record, index">
            <template>
              <a-popconfirm title="确定要删除该明细吗？"
                            @confirm="handleDeleteExtendsField(record, index)"
                            okText="确认"
                            cancelText="取消">
                <a href="#">删除</a>
              </a-popconfirm>
            </template>
          </span>
        </a-table>
      </a-form>
      <search-temp ref="searchTemp"
                   @ok="confirm"></search-temp>
    </a-spin>
  </a-modal>
</template>

<script>
import { save, getById, update, listDefaultField } from '@/api/cms/model'
import searchTemp from './searchTemp'
import pick from 'lodash.pick'
export default {
  components: {
    searchTemp
  },
  data() {
    return {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 13
        }
      },
      modalTitle: '',
      modalOpera: 0, // 0：新增 1：编辑
      visible: false,
      confirmLoading: false,
      modelOptions: [
        {
          label: '含子模型',
          value: 'hasChild'
        },
        // {
        //   label: '含图片',
        //   value: 'hasImages'
        // },
        {
          label: '含附件',
          value: 'hasFiles'
        }
      ],
      moptions: [],
      fields: [],
      checkDefaultFields: [],
      dataSource: [],
      inputType: [],
      form: this.$form.createForm(this),
      extendsField: [
        {
          name: 'code',
          type: 'text',
          required: true
        },
        {
          name: 'inputType',
          type: 'select',
          required: true
        },
        {
          name: 'name',
          type: 'text',
          required: true
        },
        {
          name: 'isRequired',
          type: 'checkbox',
          required: true
        },
        {
          name: 'isSearch',
          type: 'checkbox',
          required: true
        },
        {
          name: 'defaultValue',
          type: 'text',
          required: false
        },
        {
          name: 'maxlength',
          type: 'number',
          required: true
        },
        {
          name: 'description',
          type: 'textarea',
          required: false
        },
        {
          name: 'sort',
          type: 'number',
          required: false
        }
      ],
      // 表头
      columns: [
        {
          title: '编码',
          dataIndex: 'code',
          align: 'center',
          width: '140px',
          scopedSlots: {
            customRender: 'code'
          }
        },
        {
          title: '字段类型',
          dataIndex: 'inputType',
          align: 'center',
          width: '100px',
          scopedSlots: {
            customRender: 'inputType'
          }
        },
        {
          title: '名称',
          dataIndex: 'name',
          align: 'center',
          width: '120px',
          scopedSlots: {
            customRender: 'name'
          }
        },
        {
          title: '必填',
          dataIndex: 'isRequired',
          align: 'center',
          width: '100px',
          scopedSlots: {
            customRender: 'isRequired'
          }
        },
        {
          title: '可搜索',
          dataIndex: 'isSearch',
          align: 'center',
          width: '100px',
          scopedSlots: {
            customRender: 'isSearch'
          }
        },
        {
          title: '默认值',
          dataIndex: 'defaultValue',
          align: 'center',
          width: '100px',
          scopedSlots: {
            customRender: 'defaultValue'
          }
        },
        {
          title: '最大长度',
          dataIndex: 'maxlength',
          align: 'center',
          width: '100px',
          scopedSlots: {
            customRender: 'maxlength'
          }
        },
        {
          title: '描述',
          dataIndex: 'description',
          align: 'center',
          width: '100px',
          scopedSlots: {
            customRender: 'description'
          }
        },
        {
          title: '排序',
          dataIndex: 'sort',
          align: 'center',
          width: '100px',
          scopedSlots: {
            customRender: 'sort'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: '80px',
          scopedSlots: {
            customRender: 'action'
          }
        }
      ]
    }
  },
  created() {
    this.selectInputType()
    listDefaultField({}).then(response => {
      this.fields = response.res
    })
  },
  methods: {
    add() {
      this.modal('新建模型', 0)
    },
    edit(record) {
      const that = this
      this.modal('编辑模型', 1)
      getById({
        pk: record.id
      }).then(response => {
        const result = response.res
        this.form.setFieldsValue(
          pick(
            result,
            'id',
            'parentId',
            'name',
            'templatePath',
            'defaultFieldList'
          )
        )
        if (result.extendFieldList) {
          this.setDataSource(JSON.parse(result.extendFieldList))
        }
        if (result.defaultFieldList) {
          const defaultFieldList = JSON.parse(result.defaultFieldList)
          if (defaultFieldList.length > 0) {
            this.fields = defaultFieldList
            defaultFieldList.forEach(function(item, index) {
              if (item.initCheck) {
                that.checkDefaultFields.push(item.fieldName)
              }
            })
          }
        }
        this.setModelOptions(result)
      })
    },
    modal(title, opera) {
      this.modalTitle = title
      this.modalOpera = opera
      this.visible = true
      this.clearDataSource()
      this.form.resetFields()
    },
    confirm(path) {
      this.form.setFieldsValue({ templatePath: path })
    },
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      // this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          const param = this.bulidData(values)
          this.confirmLoading = true
          console.log(param)
          if (this.modalOpera === 0) {
            save(param).then(response => {
              if(response.code===0){
                this.$message.info(response.msg)
                this.$emit('ok')
                this.handleCancel()
              }else{
                 this.$message.error(response.msg)
              }
            })
          } else if (this.modalOpera === 1) {
            update(param).then(response => {
              if(response.code===0){
                this.$message.info(response.msg)
                this.$emit('ok')
                this.handleCancel()
              }else{
                 this.$message.error(response.msg)
              }
            })
          }
        }
        this.confirmLoading = false
      })
    },
    bulidData(values) {
      console.log(this.fields)
      const param = {
        id: values.id,
        name: values.name,
        templatePath: values.templatePath,
        hasChild: this.moptions.indexOf('hasChild') >= 0,
        hasFiles: this.moptions.indexOf('hasFiles') >= 0,
        hasImages: this.moptions.indexOf('hasImages') >= 0,
        defaultFieldList: JSON.stringify(this.fields),
        extendFieldList: JSON.stringify(this.dataSource)
      }
      return param
    },
    handleCancel() {
      this.moptions = []
      this.initFields()
      this.checkDefaultFields = []
      this.visible = false
      this.confirmLoading = false
    },
    onChangeMoption(moption) {
      const value = moption.target.value
      if (moption.target.checked) {
        this.moptions.push(value)
      } else {
        const index = this.moptions.indexOf(value)
        this.moptions.splice(index, 1)
      }
    },
    checkDefaultField(e) {
      //  选中 系统内置的 checkbox
      if (e.target.checked) {
        this.checkDefaultFields.push(e.target.value)
      } else {
        const index = this.checkDefaultFields.indexOf(e.target.value)
        if (index >= 0) {
          this.checkDefaultFields.splice(index, 1)
        }
      }
      this.getDefaultFieldByCode(e.target.value).initCheck = e.target.checked
    },
    getDefaultFieldByCode(code) {
      let field = null
      if (this.fields.length > 0) {
        this.fields.forEach(function(item, index) {
          if (item.fieldName === code) {
            field = item
          }
        })
        return field
      }
    },
    setModelOptions(obj) {
      const that = this
      this.modelOptions.forEach(function(item, index) {
        if (obj && obj[item.value]) {
          that.moptions.push(item.value)
        }
      })
    },
    onSearchTemp() {
      this.$refs.searchTemp.selectTemp()
    },
    handleAddExtendsField() {
      const newData = {
        code: '',
        inputType: this.inputType[0].value,
        name: '',
        isRequired: false,
        isSearch: false,
        defaultValue: '',
        maxlength: '',
        description: '',
        sort: 0,
        id: Date.now()
      }
      this.dataSource = [...this.dataSource, newData]
    },
    handleDeleteExtendsField(record, index) {
      this.dataSource.splice(index, 1)
    },
    setDataSource(data) {
      this.dataSource = data
    },
    clearDataSource() {
      this.dataSource = []
    },
    initFields() {
      this.fields.forEach(function(item, index) {
        if (item.fieldName !== 'title') {
          item.initCheck = false
          item.initSwitch = false
          item.reFieldNote = item.fieldNote
        }
      })
    },
    handleChange(e, key, column, index, inputType) {
      const newData = [...this.dataSource]
      const target = newData.filter(item => key === item.id)[0]
      if (target) {
        if (inputType === 'checkbox') {
          target[column] = e.target.checked
        } else {
          target[column] = e instanceof Object ? e.target.value : e
        }
      }
      console.log(this.dataSource)
    },
    selectInputType() {
      const inputTypes = [
        {
          value: 'text',
          label: '输入框'
        },
        {
          value: 'textarea',
          label: '区域框'
        },
        {
          value: 'number',
          label: '数字'
        },
        {
          value: 'date',
          label: '日期'
        },
        {
          value: 'file',
          label: '文件'
        },
        {
          value: 'picture',
          label: '图片'
        },
        {
          value: 'boolean',
          label: '开关框'
        }
      ]
      this.inputType = inputTypes
    }
  }
}
</script>
